import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import sys
import os

# 添加src和styles到路径
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'src'))
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'styles'))

from supplier_management import SupplierManager
from models.inventory_model import InventoryAnalyzer
from common_styles import apply_common_styles, create_page_title, create_metric_card

# 应用统一样式
apply_common_styles()

# 初始化供应商管理器
@st.cache_resource
def init_supplier_manager():
    return SupplierManager()

supplier_manager = init_supplier_manager()

# 页面标题
create_page_title("供应商管理系统", "🏭")

# 侧边栏功能选择
st.sidebar.title("功能菜单")
function = st.sidebar.selectbox(
    "选择功能",
    ["📊 供应商概览", "➕ 新增供应商", "📝 供应商信息管理", "📈 供应商绩效分析", "⚖️ 供应商评估", "📋 采购历史"]
)

# 供应商概览
if function == "📊 供应商概览":
    st.header("供应商概览")
    
    # 关键指标
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.markdown(create_metric_card("156", "总供应商数", "+12"), unsafe_allow_html=True)
    
    with col2:
        st.markdown(create_metric_card("89", "活跃供应商", "+5"), unsafe_allow_html=True)
    
    with col3:
        st.markdown(create_metric_card("4.2", "平均评分", "+0.1"), unsafe_allow_html=True)
    
    with col4:
        st.markdown(create_metric_card("¥2.8M", "本月采购额", "+15%"), unsafe_allow_html=True)
    
    st.markdown("---")
    
    # 供应商分布图表
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("供应商地区分布")
        region_data = pd.DataFrame({
            '地区': ['华东', '华南', '华北', '西南', '华中', '东北', '西北'],
            '供应商数量': [45, 32, 28, 18, 15, 12, 6]
        })
        fig_region = px.pie(region_data, values='供应商数量', names='地区', 
                           title="供应商地区分布")
        st.plotly_chart(fig_region, use_container_width=True)
    
    with col2:
        st.subheader("供应商类别分布")
        category_data = pd.DataFrame({
            '类别': ['原材料', '包装材料', '设备配件', '服务商', '其他'],
            '数量': [68, 34, 28, 18, 8]
        })
        fig_category = px.bar(category_data, x='类别', y='数量',
                             title="供应商类别分布")
        st.plotly_chart(fig_category, use_container_width=True)
    
    # 供应商评级分布
    st.subheader("供应商评级分布")
    rating_data = pd.DataFrame({
        '评级': ['A级', 'B级', 'C级', 'D级'],
        '数量': [42, 58, 38, 18],
        '占比': [26.9, 37.2, 24.4, 11.5]
    })
    
    col1, col2 = st.columns([2, 1])
    with col1:
        fig_rating = px.bar(rating_data, x='评级', y='数量', 
                           color='评级', title="供应商评级分布")
        st.plotly_chart(fig_rating, use_container_width=True)
    
    with col2:
        st.dataframe(rating_data, use_container_width=True, height=200)

# 新增供应商
elif function == "➕ 新增供应商":
    st.header("新增供应商")
    
    with st.form("add_supplier_form"):
        col1, col2 = st.columns(2)
        
        with col1:
            supplier_name = st.text_input("供应商名称*")
            supplier_code = st.text_input("供应商编码*")
            contact_person = st.text_input("联系人*")
            phone = st.text_input("联系电话*")
            email = st.text_input("邮箱地址")
        
        with col2:
            address = st.text_area("详细地址")
            category = st.selectbox("供应商类别", 
                                  ["原材料", "包装材料", "设备配件", "服务商", "其他"])
            region = st.selectbox("所属地区", 
                                ["华东", "华南", "华北", "西南", "华中", "东北", "西北"])
            credit_rating = st.selectbox("信用等级", ["AAA", "AA", "A", "BBB", "BB", "B"])
            payment_terms = st.selectbox("付款条件", ["现金", "30天", "60天", "90天"])
        
        # 业务信息
        st.subheader("业务信息")
        col3, col4 = st.columns(2)
        
        with col3:
            main_products = st.text_area("主要产品/服务")
            annual_capacity = st.number_input("年产能", min_value=0)
        
        with col4:
            certifications = st.text_area("资质认证")
            cooperation_years = st.number_input("合作年限", min_value=0, max_value=50)
        
        submitted = st.form_submit_button("提交")
        
        if submitted:
            if supplier_name and supplier_code and contact_person and phone:
                # 这里应该调用实际的数据库插入操作
                st.success(f"供应商 '{supplier_name}' 添加成功！")
                st.balloons()
            else:
                st.error("请填写所有必填字段（标*的字段）")

# 供应商信息管理
elif function == "📝 供应商信息管理":
    st.header("供应商信息管理")
    
    # 搜索和筛选
    col1, col2, col3 = st.columns(3)
    with col1:
        search_term = st.text_input("搜索供应商", placeholder="输入供应商名称或编码")
    with col2:
        filter_category = st.selectbox("筛选类别", ["全部", "原材料", "包装材料", "设备配件", "服务商", "其他"])
    with col3:
        filter_status = st.selectbox("筛选状态", ["全部", "活跃", "暂停", "黑名单"])
    
    # 模拟供应商数据
    suppliers_data = pd.DataFrame({
        '供应商编码': ['SUP001', 'SUP002', 'SUP003', 'SUP004', 'SUP005'],
        '供应商名称': ['华东化工有限公司', '南方包装材料厂', '北京设备制造', '上海物流服务', '广州原料供应'],
        '类别': ['原材料', '包装材料', '设备配件', '服务商', '原材料'],
        '联系人': ['张经理', '李总', '王工程师', '陈主管', '刘经理'],
        '电话': ['021-12345678', '020-87654321', '010-11223344', '021-99887766', '020-55443322'],
        '状态': ['活跃', '活跃', '暂停', '活跃', '活跃'],
        '评级': ['A', 'B', 'A', 'C', 'B'],
        '合作年限': [5, 3, 8, 2, 6]
    })
    
    # 显示供应商列表
    st.subheader("供应商列表")
    
    # 应用筛选
    filtered_data = suppliers_data.copy()
    if search_term:
        filtered_data = filtered_data[
            filtered_data['供应商名称'].str.contains(search_term, case=False, na=False) |
            filtered_data['供应商编码'].str.contains(search_term, case=False, na=False)
        ]
    if filter_category != "全部":
        filtered_data = filtered_data[filtered_data['类别'] == filter_category]
    if filter_status != "全部":
        filtered_data = filtered_data[filtered_data['状态'] == filter_status]
    
    # 显示筛选后的数据
    st.dataframe(filtered_data, use_container_width=True, height=300)
    
    # 批量操作
    st.subheader("批量操作")
    col1, col2, col3 = st.columns(3)
    with col1:
        if st.button("导出Excel"):
            st.success("供应商数据已导出到Excel文件")
    with col2:
        if st.button("批量更新状态"):
            st.info("请选择要更新的供应商")
    with col3:
        uploaded_file = st.file_uploader("批量导入", type=['csv', 'xlsx'])
        if uploaded_file:
            st.success("文件上传成功，正在处理...")

# 供应商绩效分析
elif function == "📈 供应商绩效分析":
    st.header("供应商绩效分析")
    
    # 时间范围选择
    col1, col2 = st.columns(2)
    with col1:
        start_date = st.date_input("开始日期", datetime.now() - timedelta(days=90))
    with col2:
        end_date = st.date_input("结束日期", datetime.now())
    
    # 绩效指标概览
    st.subheader("关键绩效指标")
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("平均交付及时率", "94.5%", "2.1%")
    with col2:
        st.metric("平均质量合格率", "98.2%", "0.8%")
    with col3:
        st.metric("平均响应时间", "2.3天", "-0.5天")
    with col4:
        st.metric("成本节约率", "8.7%", "1.2%")
    
    # 供应商绩效排名
    st.subheader("供应商绩效排名（Top 10）")
    performance_data = pd.DataFrame({
        '排名': range(1, 11),
        '供应商名称': ['华东化工', '南方包装', '北京设备', '上海物流', '广州原料', 
                    '深圳科技', '天津制造', '重庆材料', '西安工业', '成都供应'],
        '综合评分': [95.2, 92.8, 91.5, 89.7, 88.9, 87.3, 86.1, 85.4, 84.2, 83.8],
        '交付及时率': ['98%', '95%', '94%', '92%', '91%', '89%', '88%', '87%', '86%', '85%'],
        '质量合格率': ['99%', '98%', '99%', '97%', '98%', '96%', '97%', '95%', '94%', '96%'],
        '成本竞争力': ['A', 'A', 'B', 'A', 'B', 'B', 'C', 'B', 'C', 'B']
    })
    
    st.dataframe(performance_data, use_container_width=True)
    
    # 绩效趋势图
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("交付及时率趋势")
        dates = pd.date_range(start=start_date, end=end_date, freq='W')
        delivery_trend = pd.DataFrame({
            '日期': dates,
            '及时率': [92 + i*0.5 + (i%3)*2 for i in range(len(dates))]
        })
        fig_delivery = px.line(delivery_trend, x='日期', y='及时率', 
                              title="交付及时率趋势")
        st.plotly_chart(fig_delivery, use_container_width=True)
    
    with col2:
        st.subheader("质量合格率趋势")
        quality_trend = pd.DataFrame({
            '日期': dates,
            '合格率': [96 + i*0.3 + (i%2)*1 for i in range(len(dates))]
        })
        fig_quality = px.line(quality_trend, x='日期', y='合格率',
                             title="质量合格率趋势")
        st.plotly_chart(fig_quality, use_container_width=True)

# 供应商评估
elif function == "⚖️ 供应商评估":
    st.header("供应商评估")
    
    # 评估维度设置
    st.subheader("评估维度权重设置")
    col1, col2 = st.columns(2)
    
    with col1:
        quality_weight = st.slider("质量权重", 0, 100, 30)
        delivery_weight = st.slider("交付权重", 0, 100, 25)
        cost_weight = st.slider("成本权重", 0, 100, 20)
    
    with col2:
        service_weight = st.slider("服务权重", 0, 100, 15)
        innovation_weight = st.slider("创新权重", 0, 100, 10)
        total_weight = quality_weight + delivery_weight + cost_weight + service_weight + innovation_weight
        st.metric("总权重", f"{total_weight}%")
    
    if total_weight != 100:
        st.warning("权重总和应为100%")
    
    # 供应商评估结果
    st.subheader("评估结果")
    
    evaluation_data = pd.DataFrame({
        '供应商': ['华东化工', '南方包装', '北京设备', '上海物流', '广州原料'],
        '质量得分': [95, 88, 92, 85, 90],
        '交付得分': [92, 95, 89, 88, 87],
        '成本得分': [88, 90, 85, 92, 89],
        '服务得分': [90, 87, 88, 95, 85],
        '创新得分': [85, 82, 90, 80, 83],
        '综合得分': [91.2, 89.1, 89.8, 89.5, 87.9],
        '评级': ['A', 'B', 'A', 'B', 'B']
    })
    
    st.dataframe(evaluation_data, use_container_width=True)
    
    # 雷达图显示评估结果
    st.subheader("供应商能力雷达图")
    selected_supplier = st.selectbox("选择供应商", evaluation_data['供应商'].tolist())
    
    supplier_scores = evaluation_data[evaluation_data['供应商'] == selected_supplier].iloc[0]
    
    fig_radar = go.Figure()
    fig_radar.add_trace(go.Scatterpolar(
        r=[supplier_scores['质量得分'], supplier_scores['交付得分'], 
           supplier_scores['成本得分'], supplier_scores['服务得分'], 
           supplier_scores['创新得分']],
        theta=['质量', '交付', '成本', '服务', '创新'],
        fill='toself',
        name=selected_supplier
    ))
    
    fig_radar.update_layout(
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[0, 100]
            )
        ),
        showlegend=True,
        title=f"{selected_supplier} 能力评估雷达图"
    )
    
    st.plotly_chart(fig_radar, use_container_width=True)

# 采购历史
elif function == "📋 采购历史":
    st.header("采购历史")
    
    # 筛选条件
    col1, col2, col3 = st.columns(3)
    with col1:
        supplier_filter = st.selectbox("选择供应商", ["全部", "华东化工", "南方包装", "北京设备", "上海物流", "广州原料"])
    with col2:
        date_range = st.date_input("日期范围", [datetime.now() - timedelta(days=30), datetime.now()])
    with col3:
        amount_filter = st.selectbox("金额范围", ["全部", "<10万", "10-50万", "50-100万", ">100万"])
    
    # 采购历史数据
    purchase_history = pd.DataFrame({
        '采购单号': ['PO2024001', 'PO2024002', 'PO2024003', 'PO2024004', 'PO2024005'],
        '供应商': ['华东化工', '南方包装', '北京设备', '上海物流', '广州原料'],
        '采购日期': ['2024-01-15', '2024-01-18', '2024-01-20', '2024-01-22', '2024-01-25'],
        '产品类别': ['原材料', '包装材料', '设备配件', '物流服务', '原材料'],
        '采购金额': [156000, 89000, 234000, 45000, 178000],
        '交付状态': ['已完成', '已完成', '进行中', '已完成', '已完成'],
        '质量状态': ['合格', '合格', '待检', '合格', '不合格']
    })
    
    st.dataframe(purchase_history, use_container_width=True, height=300)
    
    # 采购统计
    st.subheader("采购统计分析")
    
    col1, col2 = st.columns(2)
    
    with col1:
        # 按供应商统计采购金额
        supplier_amount = purchase_history.groupby('供应商')['采购金额'].sum().reset_index()
        fig_supplier = px.bar(supplier_amount, x='供应商', y='采购金额',
                             title="各供应商采购金额统计")
        st.plotly_chart(fig_supplier, use_container_width=True)
    
    with col2:
        # 按产品类别统计
        category_amount = purchase_history.groupby('产品类别')['采购金额'].sum().reset_index()
        fig_category = px.pie(category_amount, values='采购金额', names='产品类别',
                             title="产品类别采购占比")
        st.plotly_chart(fig_category, use_container_width=True)
    
    # 导出功能
    st.subheader("数据导出")
    col1, col2 = st.columns(2)
    with col1:
        if st.button("导出采购历史"):
            st.success("采购历史数据已导出")
    with col2:
        if st.button("生成采购报告"):
            st.success("采购报告已生成")

# 页脚
st.markdown("---")
st.markdown("**供应商管理系统** | 实时数据管理与分析")